﻿using MTQ.BLL;
using MTQ.Common;
using MTQ.IBLL;
using MTQ.Model;
using MTQ.Model.PhoneModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace MTQ.Web.Controllers
{
    public class LoginController : Controller
    {
        private IBase_UserInfoService _userInfoService = new Base_UserInfoService();
        //
        // GET: /Login/

        public ActionResult Index(string UserName, string UserInfoError)
        {
            // var c = msg;


            ViewBag.UserName = UserName;
            ViewBag.UserInfoError = UserInfoError;
            ViewBag.loginName = System.Configuration.ConfigurationManager.AppSettings.Get("loginName");

            //string[] browerCulture = HttpContext.Request.UserLanguages;
            //var language = browerCulture[0].ToLower();
            //string word = "";
            //if (language.IndexOf("cn") > -1)
            //{
            //    word = "项目报告系统";
            //}
            //else if (language.IndexOf("en") > -1)
            //{
            //    word = "Project Reporting System";
            //}
            //  ViewBag.SystemTitle = word;

            string word = "项目报告系统";
            ViewBag.SystemTitle_cn = "项目报告系统";
            ViewBag.SystemTitle_en = "Project Reporting System";


            return View();
        }
        /// <summary>
        /// 判断用户输入的信息是否正确，[HttpPost]
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="userInfo">用户的实体类</param>
        /// <param name="Code">验证码</param>
        /// <returns>返回是否执行成功的标志</returns>
        //[ProjectAuth(Roles = "Login_CheckUserInfo")]
        public ActionResult CheckUserInfo()//, string Code
        {
            // Sys_EventLogService.LogWrite("/LoginController/CheckUserInfo", this.Request, null, "登录", "使用账户" + UserName);

            string UserName = GetRequestQueryString("username");
            string Password = GetRequestQueryString("password");

            Task.Run<bool>(() =>
            {
                var t1 = Task.Run(() =>
                {
                    SaveLoginLog(Request);
                });
                return true;
            });
            //调用业务逻辑层（BLL）去校验用户是否正确,,,定义变量存取获取到的用户的错误信息
            string UserInfoError = "";
            Base_UserInfo userInfoLogin = new Base_UserInfo();
            userInfoLogin.User_UserName = UserName;
            userInfoLogin.User_Password = MD5Cryptography.MD5Encrypt(Password);
            var loginUserInfo = _userInfoService.CheckUserInfo(userInfoLogin);

            switch (loginUserInfo)
            {
                case LoginResult.PwdError:
                    UserInfoError = "密码输入错误";
                    break;
                case LoginResult.UserNotExist:
                    UserInfoError = "用户名输入错误或者您已经被禁用";
                    break;
                case LoginResult.UserIsNull:
                    UserInfoError = "用户名不能为空";
                    break;
                case LoginResult.PwdIsNUll:
                    UserInfoError = "密码不能为空";
                    break;
                case LoginResult.OK:
                    UserInfoError = "OK";
                    break;
                case LoginResult.UserActivation:
                    UserInfoError = "用户名未激活";
                    break;
                default:
                    UserInfoError = "未知错误，请您检查您的数据库";
                    break;
            }

            //登录成功保存用户信息
            if (loginUserInfo == LoginResult.OK)
            {

                //HttpCookie cookie = new HttpCookie("LoginUserInfo_etrial");  //声明一个Key为person的Cookie对象
                //cookie.Expires = DateTime.Now.AddHours(10);  //设置Cookie的有效期
                //cookie.Value = userInfoLogin.Base_UserInfoEmail;  //将cookie的Value值设置为
                //cookie.Path = "/";
                //Response.SetCookie(cookie);

                //Session.Clear();
                //session.removeAttribute
                //保存登陆用户账号信息
                Base_UserInfo userInfoShow = _userInfoService.LoadEntities(p => p.User_UserName == UserName).FirstOrDefault();
                Base_RoleService base_RoleService = new Base_RoleService();
                Guid guidadmin = new Guid("17f1a2a8-011d-4ddd-8a88-7643a06b22ed");
                List<Guid> listrole = base_RoleService.LoadEntities(x => x.Role_GroupId == guidadmin && x.Role_Available == "Y").Select(x => x.Role_Id).ToList();
                List<string> listrowls = new List<string>();
                foreach (var item in listrole)
                {
                    if (item != null)
                    {
                        listrowls.Add(item.ToString());
                    }
                }

                if (userInfoShow.User_UserName == "Admin" || (userInfoShow.Role_Id != null && listrowls.Contains(userInfoShow.Role_Id)))
                {
                    userInfoShow.IsSuperAdmin = true;
                }
                //Session["UserInfo"] = userInfoShow;

                //保存用户可访问的菜单栏信息
                //IBase_MenuService ims = new Base_MenuService();
                //var listMenu = ims.GetMenuByUserId(userInfoShow).Distinct().ToList();//去除重复数据
                ////存Session
                //Session["userMenu"] = listMenu;
                ////将用户访问的数据存入Session
                //UserDataAccess userDataAcesses = new UserDataAccess();
                //Session["UserDataAccess"] = GetUserDataAccess(UserName);

                //读取权限
                List<string> listAction = new List<string>();

                //Session["listUserAction"] = GetUserMenuIds(userInfoShow);
                List<Guid> list = GetUserMenuIds(userInfoShow);
                Session["listUserMenuIds"] = list;
                Session["listUserMenu"] = GetUserBase_Menu(list);

                Session["listUserButtonIds"] = Base_UserInfoService.GetUserButton(userInfoShow);
                //Session["listProejctNumbers"] = ProjectInfoService.GetUserControlProjectNumber(userInfoShow);
                //Session["listUserEditProjectNumber"] = userInfoShow.listUserEditProjectNumber;

                Session["UserInfo"] = userInfoShow;

                Base_LocalUser localuser = new Base_LocalUserService().LoadEntities(x => x.User_Id == userInfoShow.User_Id).FirstOrDefault();
                if (localuser != null)
                {
                    Session["CultureInfoName"] = localuser.LanguageName;
                }

                userInfoShow.pwd = Password;


                //var redisCache = CacheFactory.CaChe();
                //redisCache.Write<Base_UserInfo>("Base_UserInfo"+ userInfoShow.User_Id, userInfoShow);

                return Json(new { code = 200, UserName = UserName, UserInfoError = "OK" });
            }

            #region ----使用if else来判断信息----
            //if (loginUserInfo == LoginResult.UserIsNull)
            //{
            //    UserInfoError = "用户名不能为空";
            //}
            //else if (loginUserInfo == LoginResult.PwdIsNUll)
            //{
            //    UserInfoError = "密码不能为空";
            //}
            //else if (loginUserInfo == LoginResult.UserNotExist)
            //{
            //    UserInfoError = "用户名输入错误";
            //}
            //else if (loginUserInfo == LoginResult.PwdError)
            //{
            //    UserInfoError = "密码输入错误";
            //}
            //else if (loginUserInfo == LoginResult.OK)
            //{
            //    UserInfoError = "OK";
            //}
            //else
            //{
            //    UserInfoError = "未知错误，请您检查您的数据库";
            //} 
            #endregion

            return Json(new { code = 101, UserName = UserName, UserInfoError = UserInfoError });
            // return RedirectToAction("Index", "Login", new { UserName = UserName, UserInfoError = UserInfoError });
            //return   ;
        }

        private void SaveLoginLog(HttpRequestBase httpRequest)
        {
            string UserName = GetRequestQueryString("username");
            //string Password = GetRequestQueryString("password");
            var UserHostAddress = httpRequest.UserHostAddress;
            var UserAgent = httpRequest.UserAgent;

            Log_Login log_Login = new Log_Login()
            {
                Log_UserName = UserName,
                Log_LoginTime = System.DateTime.Now,
                Log_BrowserInfo = UserAgent,
                Log_LoginIP = UserHostAddress,
            };

            Log_LoginService.InsertLog(log_Login);
        }

        private List<Guid> GetUserMenuIds(Base_UserInfo userInfo)
        {
            Base_UserRoleService urs = new Base_UserRoleService();
            List<Guid> listRoles = urs.LoadEntities(x => x.Base_UserId == userInfo.User_Id).Select(x => x.Base_RoleId).ToList();

            //Base_RoleAuthService ras = new Base_RoleAuthService();
            //List<Guid> listAuths = ras.LoadEntities(x => listRoles.Contains(x.Role_Id)).Select(x => x.Auth_Id).ToList();
            //Base_AuthService ass = new Base_AuthService();
            //List<Guid> listMenus = ass.LoadEntities(x => listAuths.Contains(x.Auth_Id)).Select(x => x.Menu_Id).ToList();

            Base_RoleButtonService ras = new Base_RoleButtonService();
            List<Guid> listButtonIds = ras.LoadEntities(x => listRoles.Contains(x.Role_Id)).Select(x => x.Button_Id).ToList();

            Base_ButtonService ass = new Base_ButtonService();
            List<Guid?> listMenuIds = new List<Guid?>();
            foreach (var item in ass.LoadEntities(x => listButtonIds.Contains(x.Button_Id)).Select(x => x.Menu_Id).ToList())
            {
                listMenuIds.Add(item);
            }


            Base_MenuService bms = new Base_MenuService();
            List<Base_Menu> listMenus = bms.LoadEntities(x => x.Menu_Status == 1).ToList();

            List<Guid> listresult = new List<Guid>();
            Base_MenuService.MenuIDs(listMenus, listMenuIds, listresult);

            //超级管理员拥有所有权限
            if (userInfo.IsSuperAdmin)
            {
                listresult = bms.LoadEntities(x => x.Menu_Type == 1).Select(x => x.Menu_Id).ToList();
            }
            return listresult;
        }

        private List<Base_Menu> GetUserBase_Menu(List<Guid> list)
        {
            Base_MenuService bms = new Base_MenuService();
            List<Base_Menu> listMenus = bms.LoadEntities(x => list.Contains(x.Menu_Id)).ToList();

            return listMenus;
        }


        private List<Guid> GetUserActionIds(Base_UserInfo userInfo)
        {
            Base_UserRoleService urs = new Base_UserRoleService();
            List<Guid> listRoles = urs.LoadEntities(x => x.Base_UserId == userInfo.User_Id).Select(x => x.Base_RoleId).ToList();

            //Base_RoleAuthService ras = new Base_RoleAuthService();
            //List<Guid> listAuths = ras.LoadEntities(x => listRoles.Contains(x.Role_Id)).Select(x => x.Auth_Id).ToList();
            //Base_AuthService ass = new Base_AuthService();
            //List<Guid> listMenus = ass.LoadEntities(x => listAuths.Contains(x.Auth_Id)).Select(x => x.Menu_Id).ToList();

            Base_RoleButtonService ras = new Base_RoleButtonService();
            List<Guid> listButtonIds = ras.LoadEntities(x => listRoles.Contains(x.Role_Id)).Select(x => x.Button_Id).ToList();

            Base_ButtonService ass = new Base_ButtonService();
            List<Guid?> listMenuIds = new List<Guid?>();
            foreach (var item in ass.LoadEntities(x => listButtonIds.Contains(x.Button_Id)).Select(x => x.Menu_Id).ToList())
            {
                listMenuIds.Add(item);
            }

            Base_MenuService bms = new Base_MenuService();
            List<Base_Menu> listMenus = bms.LoadEntities(x => x.Menu_Status == 1).ToList();

            List<Guid> listresult = new List<Guid>();
            Base_MenuService.MenuIDs(listMenus, listMenuIds, listresult);

            return listresult;
        }

        //private UserDataAccess GetUserDataAccess(string UserName)
        //{
        //    UserDataAccess userDataAcess = new UserDataAccess();

        //    return userDataAcess;
        //}


        /// <summary>
        /// 验证码的实现
        /// </summary>
        /// <returns>返回验证码</returns>
        /// 
        //[ProjectAuth(Roles = "Login_CheckCode")]
        public ActionResult CheckCode()
        {
            //首先实例化验证码的类
            KenceryValidateCode validateCode = new KenceryValidateCode();
            //生成验证码指定的长度
            //string code = validateCode.CreateValidateCode(5);
            string code = "11111";
            //将验证码赋值给Session变量
            //Session["ValidateCode"] = code;
            this.TempData["ValidateCode"] = code;
            //创建验证码的图片
            byte[] bytes = validateCode.CreateValidateGraphic(code);
            //最后将验证码返回
            return File(bytes, @"image/jpeg");
        }


        //public ActionResult KeepSessionAlive()
        //{
        //    if (Session["UserInfo"] == null || Session["userMenu"] == null || Session["UserDataAccess"] == null || Session["listUserAction"] == null)
        //    {
        //        string username = Request.Cookies["LoginUserInfo_etrial"].Value;
        //        if (!string.IsNullOrWhiteSpace(username))
        //        {
        //            HttpCookie cookie = new HttpCookie("LoginUserInfo_etrial");  //声明一个Key为person的Cookie对象
        //            cookie.Expires = DateTime.Now.AddHours(10);  //设置Cookie的有效期
        //            cookie.Value = username;  //将cookie的Value值设置为
        //            cookie.Path = "/";
        //            Response.SetCookie(cookie);

        //            Session.Clear();
        //            //session.removeAttribute
        //            //保存登陆用户账号信息
        //            Base_UserInfo userInfoShow = _userInfoService.LoadEntities(p => p.Email == username).FirstOrDefault();
        //            Session["UserInfo"] = userInfoShow;

        //            //保存用户可访问的菜单栏信息
        //            IS_MenuService ims = new S_MenuService();
        //            var listMenu = ims.GetMenuByUserId(userInfoShow).Distinct().ToList();//去除重复数据
        //            //存Session
        //            Session["userMenu"] = listMenu;

        //            //将用户访问的数据存入Session

        //            UserDataAccess userDataAcesses = new UserDataAccess();

        //            Session["UserDataAccess"] = GetUserDataAccess(username);

        //            //读取权限
        //            List<string> listAction = new List<string>();

        //            Session["listUserAction"] = GetUserMenu(username);
        //        }
        //    }
        //    return Json(true, JsonRequestBehavior.AllowGet);
        //}

        public ActionResult ApplyResetPassword()
        {
            var username = GetRequestQueryString("username");



            M_EmailSendService m_EmailSendService = new M_EmailSendService();
            Base_UserInfoService base_UserInfoService = new Base_UserInfoService();
            Base_UserInfo listuserinfo = base_UserInfoService.LoadEntities(x => x.User_UserName == username).FirstOrDefault();
            if (listuserinfo == null)
            {
                return Json("False");
            }


            //m_EmailSendService.url = Request.Url.Scheme + "://" + Request.Url.Authority;
            //m_EmailSendService.Account = listuserinfo.User_UserName;
            //if (!string.IsNullOrEmpty(listuserinfo.User_Email))
            //{
            //    m_EmailSendService.CreateResetPasswordEmail(listuserinfo.User_Email, listuserinfo.User_RealName);
            //}
            //else if (listuserinfo.User_UserName.IndexOf("@") > -1 && listuserinfo.User_UserName.IndexOf(".") > -1)
            //{
            //    m_EmailSendService.CreateResetPasswordEmail(listuserinfo.User_UserName, listuserinfo.User_RealName);
            //}

            return Json("True");

        }

        public ActionResult ResetPassword()
        {
            var username = GetRequestQueryString("username");
            if (string.IsNullOrEmpty(username))
            {
                ViewBag.LoginName = "";
                return View();
            }

            Base_UserInfoService base_UserInfoService = new Base_UserInfoService();

            string User_UserName = "";
            try
            {
                User_UserName = MD5Cryptography.MD5Decrypt(username);
            }
            catch
            {
                ViewBag.LoginName = "";
                return View();
            }

            if (System.DateTime.Now.AddMinutes(-20) > User_UserName.Substring(0, 19)._ToDatetime())
            {
                ViewBag.LoginName = "";
                return View();
            }

            string un = User_UserName.Substring(19);
            Base_UserInfo base_UserInfo = base_UserInfoService.LoadEntities(x => x.User_UserName == un).FirstOrDefault();
            if (base_UserInfo == null)
            {
                ViewBag.LoginName = "";
            }
            else
            {
                ViewBag.LoginName = username;
            }


            return View();
        }

        public ActionResult ModifyResetPassword()
        {
            var L_pass = GetRequestQueryString("L_pass");
            var username = GetRequestQueryString("username");
            var L_pass_again = GetRequestQueryString("L_pass_again");

            Base_UserInfoService base_UserInfoService = new Base_UserInfoService();

            string User_UserName = "";
            try
            {
                User_UserName = MD5Cryptography.MD5Decrypt(username);
            }
            catch
            {
                return Json("False");
            }

            if (System.DateTime.Now.AddMinutes(-25) > User_UserName.Substring(0, 19)._ToDatetime())
            {
                return Json("False");
            }

            string un = User_UserName.Substring(19);
            Base_UserInfo base_UserInfo = base_UserInfoService.LoadEntities(x => x.User_UserName == un).FirstOrDefault();
            if (base_UserInfo == null)
            {
                return Json("False");
            }
            else
            {
                base_UserInfo.User_Password = MD5Cryptography.MD5Encrypt(L_pass);
                base_UserInfoService.UpdateEntity(base_UserInfo);
            }

            return Json("True");
        }

        public string GetRequestQueryString(string key)
        {
            try
            {
                if (Request.QueryString[key] != null)
                {
                    return Request.QueryString[key];
                }
                else
                {
                    return Request.Form[key];
                }


            }
            catch
            {
                return null;
            }
        }


        public ActionResult Cross(string userinfo)
        {
            string struserinfo = MD5Cryptography.MD5Decrypt(userinfo);
            Group_UserInfo base_UserInfo = JsonSerializerHelper.GetJsonEntity<Group_UserInfo>(struserinfo);
            //if (CheckUserInfo(base_UserInfo.User_UserName, base_UserInfo.pwd)) { 
            //}
            return RedirectToAction("CheckUserInfo", "Login", new { UserName = base_UserInfo.User_UserName, Password = base_UserInfo.User_Password });
        }

        public ActionResult Async()
        {


            return RedirectToAction("Index", "Login");
        }

    }
}
